#coding=utf8

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myfeeds.settings")

import django
if django.VERSION >= (1, 7):        #自动判断版本
    django.setup()
    
from feed.models import Article
from rss import main
import Queue

print u'数据库操作'

def write():
    print u'数据库写入'
    objs=Article.objects.all()
    obj_set=set(list(objs))
    
    # obj_set=set(objs.link)
    # obj_set=set()
    # for obj in objs:
        # obj_set.add(obj.link)
        
    rst = main.Producer()
    # new_feed_list=[]
    new_feed_list=Queue.Queue()
    for item in rst:
        atcl=Article()
        atcl.title=item.title
        atcl.link=item.link
        atcl.pubDate= item.pubDate
        atcl.description=item.description
        atcl.name=item.name
        # if atcl.link not in obj_set:
        if atcl not in obj_set:
            new_feed_list.put(atcl)
        # atcl.save()
    
    # lst=list(new_feed_list)
    
    lst=[]
    while True:
        if new_feed_list.empty():
            break        
        lst.append(new_feed_list.get())
        
    Article.objects.bulk_create(lst)
    
    '''
    # Article.objects.bulk_create(new_feed_list)
        
        # Article.objects.get_or_create(
        # Article.objects.create(
            # title=item.title,
            # link=item.link,
            # pubDate=item.pubDate,
            # description=item.description
            # )     
    '''

def delete():
    print u'数据库清除'
    Article.objects.all().delete()
    
    
if __name__=="__main__":
    write()
